/*
 * @Author: Clark
 * @Email: haixuanwoTxh@gmail.com
 * @Date: 2021-11-27 11:59:51
 * @LastEditors: Clark
 * @LastEditTime: 2021-12-10 18:49:24
 * @Description: file content
 */

#ifndef ID_MANAGER_H
#define ID_MANAGER_H

#include <list>

class IdManager
{
public:
    IdManager()
    {
        idList = new std::list<std::pair<unsigned int, int>>;
        idList->clear();
    }

    bool add_id(unsigned int userId, int clientSocketFd)
    {
        idList->push_back(std::make_pair(userId, clientSocketFd));
        return true;
    }

    bool delete_id(int clientSocketFd)
    {
        for(auto it = idList->begin(); it != idList->end(); ++it)
        {
            if(it->second == clientSocketFd)
            {
                idList->erase(it);
                return true;
            }
        }

        return true;
    }

    unsigned long get_id_num()
    {
        return idList->size();
    }

    std::pair<unsigned int, int> get_clientFd_userID(int index)
    {
        auto it = idList->begin();

        while (index > 1)
        {
            index--;
            if (it != idList->end())
                it++;
        }

        return *it;
    }

    bool find_userID(int clientSocketFd, unsigned int &userID)
    {
        for (auto node : *idList)
        {
            if (node.second == clientSocketFd)
            {
                userID = node.first;
                return true;
            }
        }
        return false;
    }

    bool find_clientSocketFd(unsigned int userID, int &clientSocketFd)
    {
        for (auto node : *idList)
        {
            if (node.first == userID)
            {
                clientSocketFd = node.second;
                return true;
            }
        }
        return false;
    }

    ~IdManager()
    {
        delete idList;
    }
private:
    std::list<std::pair<unsigned int, int>> *idList; // pair.first:用户唯一标识,pair.second:客户端socket fd
};

#endif
